package com.efe.ms.esservice.web;

import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.web.bind.annotation.*;

import com.efe.ms.common.vo.PaginationVO;
import com.efe.ms.esservice.model.AmazonBrandKeyword;
import com.efe.ms.esservice.model.ProductDocument;
import com.efe.ms.esservice.service.AmazonBrandKeywordService;
import com.efe.ms.esservice.service.ProductDocumentService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * elasticsearch 搜索
 * 
 * @author hhx
 * @date 2020-11-02
 */
@Api(tags = "API搜索引擎测试用例")
@RestController
public class ProductEsSearchBaseController {

	@Resource
	private ProductDocumentService baseSearchService;
	@Resource
	private AmazonBrandKeywordService amazonBrandKeywordService;
	


	/**
	 * 新增 / 修改索引
	 * 
	 * @return
	 */
	@RequestMapping(value = "/save", method = { RequestMethod.GET })
	@ResponseBody
	@ApiOperation(value = "新增 / 修改索引")
	public String add(String id, String productDesc, String productName, String menu_name) {
		try {
			// 创建引擎库
			// baseSearchService.create(ProductDocument.class);
			ProductDocument productDocument = new ProductDocument();
			productDocument.setId(id);
			productDocument.setProductDesc(productDesc);
			productDocument.setProductName(productName);
			productDocument.setMenu_name(menu_name);
			baseSearchService.save(productDocument);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "failed";
	}

	/**
	 * 	删除索引库
	 * 	注意：删除引擎库操作在执行查询移除的引擎库会报错误！
	 * 		
	 * @param indexName
	 * @return
	 */
	@ApiOperation(value = "删除索引库")
	@RequestMapping(value = "/deleteIndex/{indexName}", method = { RequestMethod.GET })
	@ResponseBody
	public String deleteIndex(@PathVariable String indexName) {
		try {
			baseSearchService.deleteIndex(indexName);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "failed";

	}

	/**
	 * 删除索引
	 * 
	 * @return
	 */
	@ApiOperation(value = "删除索引")
	@RequestMapping(value = "/delete/{id}", method = { RequestMethod.GET })
	@ResponseBody
	public String delete(@PathVariable String id) {
		baseSearchService.delete(id);
		return "success";
	}

	/**
	 * 清空索引
	 * 
	 * @return
	 */
	@ApiOperation(value = "清空索引")
	@RequestMapping(value = "/deleteAll", method = { RequestMethod.GET })
	@ResponseBody
	public String deleteAll(@PathVariable String id) {
		baseSearchService.deleteAll();
		return "success";
	}

	/**
	 * 根据ID获取
	 * 
	 * @return
	 */
	@ApiOperation(value = "根据ID获取")
	@RequestMapping(value = "/get/{id}", method = { RequestMethod.GET })
	@ResponseBody
	public Object getById(@PathVariable String id) {
		return amazonBrandKeywordService.getById(id);
	}

	/**
	 * 根据获取全部
	 * 
	 * @return
	 */
	@ApiOperation(value = "根据获取全部有分页")
	@RequestMapping(value = "/getAll", method = { RequestMethod.GET })
	@ResponseBody
	public PaginationVO<AmazonBrandKeyword> getAll(@RequestParam(defaultValue = "0") Integer pageIndex,
			@RequestParam(defaultValue = "100") Integer pageSize) {
		try {
			List<AmazonBrandKeyword> all = amazonBrandKeywordService.getAll(pageIndex, pageSize);
			int count = baseSearchService.getCount();
			return amazonBrandKeywordService.getPageData(pageIndex, pageSize, AmazonBrandKeyword.class, all, count);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 搜索
	 * 
	 * @param keyword
	 * @return
	 */
	// @ApiOperation(value="搜索")
	@RequestMapping(value = "/query/{keyword}", method = { RequestMethod.GET })
	public List<ProductDocument> query(@PathVariable String keyword) {
		return null;
	}

	/**
	 * 
	 * @param keyword       字段名称
	 * @param keyValue      字段对应的值
	 * @param keyValusFiles 查询索引库中的字段列表 以","分割
	 * @param excludes
	 * @param indices       引擎库名
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ApiOperation(value = "多引擎库搜索匹配数据")
	@ResponseBody
	@RequestMapping(value = "/queryHit", method = { RequestMethod.GET})
	public List<Map<String, Object>> queryHit(@RequestParam(defaultValue = "0") int pageIndex,
			@RequestParam(defaultValue = "100") int pageSize, @RequestParam String keyword,
			@RequestParam String keyValue, @RequestParam String keyValusFiles, @RequestParam String excludes,
			@RequestParam String... indices) {
		// 要显示的字段列表（）
		String[] fieldNames = new String[] {};
		String[] removeNames = new String[] {};
		fieldNames = getColumnFiles(keyValusFiles, fieldNames);
		removeNames = getColumnFiles(excludes, removeNames);
		return (List<Map<String, Object>>) baseSearchService.getAllIndex(keyValue, keyword, fieldNames, removeNames,
				pageIndex, pageSize, indices);
	}

	@ApiOperation(value = "多引擎")
	@ResponseBody
	@RequestMapping(value="/getTestData",method= {RequestMethod.POST})
	public Object  getTestData(@RequestParam(defaultValue = "1") Integer pageNum,
			@RequestParam(defaultValue = "10") Integer rows, @RequestParam(required=false) Map<String,Object> map,
			HttpServletRequest requet,HttpServletResponse response) {
		
		if(null !=map&& map.size()>0) {
			System.out.println(map.get("id"));
		}
		return  "success";
		
	}
	
	/***
	 * 字符串转数组
	 * 
	 * @param keyValusFiles
	 * @param fieldNames
	 * @return
	 */
	private String[] getColumnFiles(String keyValusFiles, String[] fieldNames) {
		if (null != keyValusFiles && !"".equals(keyValusFiles.trim())) {
			boolean contains = keyValusFiles.contains(",");
			if (contains) {
				fieldNames = keyValusFiles.split(",");
			} else {
				fieldNames = new String[] { keyValusFiles };
			}
		}
		return fieldNames;
	}

	/***
	 * 指定引擎库id类型查询数据
	 * 
	 * @param pageIndex
	 * @param pageSize
	 * @param keyValue
	 * @param indexName
	 * @param fields
	 * @return 返回对应引擎库实体对象
	 */
	@ApiOperation(value = "指定引擎库匹配数据")
	@ResponseBody
	@RequestMapping(value = "queryHitPage", method = { RequestMethod.GET })
	public PaginationVO<AmazonBrandKeyword> queryHitByPage(@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "100") int pageSize, @RequestParam(required = false) String keyValue,
			@RequestParam(required = false) String keyColumn, @RequestParam(required = false) String fields) {
		page=page-1;
		Map<String, String> parm=null;
		if(null !=keyColumn && null!=keyValue ) {
			parm= new HashMap<>();
			parm.put(keyColumn, keyValue);
		}
		
//		LocalDate now = newestDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//        LocalDate todayOfLastWeek = now.minusDays(7);
//        LocalDate monday = todayOfLastWeek.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY));
//        LocalDate sunday = todayOfLastWeek.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).minusDays(2);
//        String thisWeek = monday + " - " + sunday;
//        todayOfLastWeek = now.minusDays(14);
//        monday = todayOfLastWeek.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY));
//        sunday = todayOfLastWeek.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).minusDays(2);
//        String lastWeek = monday + " - " + sunday;
		
		
		SearchSourceBuilder searchSourceBuilder = baseSearchService.getSearchSourceBuilder(parm, keyValue, page,
				pageSize, "create_time", SortOrder.ASC);
		System.out.println(searchSourceBuilder.toString());
		PaginationVO<AmazonBrandKeyword> searchGetPage = null;
		try {
			searchGetPage = amazonBrandKeywordService.searchGetPage(searchSourceBuilder, page, pageSize,
					AmazonBrandKeyword.class);
			searchGetPage.getData().stream().forEach(item ->{
				String id = item.getId();
				AmazonBrandKeyword byId = amazonBrandKeywordService.getById(id);
				Integer a= null==  item.getSearch_frequency_ranking() ? 0: Integer.parseInt(item.getSearch_frequency_ranking()) ;
	        	if(null  ==byId) {
	        		
	        	}else {
	        		Integer search_last_week_ranking = null  == byId.getSearch_frequency_ranking() ? 0:Integer.parseInt(byId.getSearch_frequency_ranking());
	            	
	            	Integer rank_up =search_last_week_ranking-a;
	            	item.setSearch_last_week_ranking(search_last_week_ranking+"");
	            	item.setRankUp(rank_up+"");
	        	}
				
			});
			
			
		} catch (Exception e) {

			e.printStackTrace();
		}
		return searchGetPage;
	}

}
